package com.lambkit.plugin.api.route.interceptor;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.authz.annotation.Logical;

import com.jfinal.kit.StrKit;
import com.lambkit.Lambkit;
import com.lambkit.common.util.StringUtils;
import com.lambkit.plugin.api.route.ApiInvocation;
import com.lambkit.plugin.auth.AuthManager;
import com.lambkit.plugin.auth.AuthUser;
import com.lambkit.plugin.jwt.JwtConfig;

public class ApiAuthTokenInterceptor extends ApiAuthInterceptor {

	AuthUser theUser = null;
	
	protected AuthUser getUser(HttpServletRequest request) {
		if(theUser==null) {
			String accessToken = request.getParameter("tk");
			accessToken = StrKit.isBlank(accessToken) ? request.getParameter("token") : accessToken;
			accessToken = StrKit.isBlank(accessToken) ? request.getParameter("accessToken") : accessToken;
			accessToken = StrKit.isBlank(accessToken) ? request.getParameter("sessionid") : accessToken;
			if(StrKit.isBlank(accessToken)) {
				JwtConfig config = Lambkit.config(JwtConfig.class);
				accessToken = request.getHeader(config.getHeader());
			}
			accessToken = StrKit.isBlank(accessToken) ? request.getHeader("sessionid") : accessToken;
			theUser = AuthManager.me().getService().authenticate(accessToken);
		}
		return theUser;
	}
	
	
	@Override
	protected boolean hasGuest(ApiInvocation inv) {
		// TODO Auto-generated method stub
		return true;
	}

	@Override
	protected boolean hasUser(ApiInvocation inv) {
		// TODO Auto-generated method stub
		AuthUser user = getUser(inv.getRequest());
		return user==null ? false : true;
	}

	@Override
	protected boolean hasAuthentication(ApiInvocation inv) {
		// TODO Auto-generated method stub
		AuthUser user = getUser(inv.getRequest());
		return user==null ? false : true;
	}

	@Override
	protected boolean hasRoles(ApiInvocation inv, String[] value, Logical logical) {
		// TODO Auto-generated method stub
		AuthUser user = getUser(inv.getRequest());
		if(user==null) {
			return false;
		}
		if(value.length < 1) {
			return true;
		}
		String roles = StringUtils.join(value, ",", null, null);
		if(logical==Logical.AND) {
			return AuthManager.me().getService().hasAllRoles(roles);
		} else {
			return AuthManager.me().getService().hasAnyRoles(roles);
		}
	}

	@Override
	protected boolean hasPermissions(ApiInvocation inv, String[] value, Logical logical) {
		// TODO Auto-generated method stub
		AuthUser user = getUser(inv.getRequest());
		if(user==null) {
			return false;
		}
		if(value.length < 1) {
			return true;
		}
		String perms = StringUtils.join(value, ",", null, null);
		if(logical==Logical.AND) {
			return AuthManager.me().getService().hasAllRules(perms);
		} else {
			return AuthManager.me().getService().hasAnyRules(perms);
		}
	}


}
